import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { useParams } from "react-router-dom";
import MDEditor from "@uiw/react-md-editor";

import {
  Typography,
  Spin,
  message,
  Row,
  Col,
  Divider,
  Input,
  Button,
  Tooltip,
  List,
  Popconfirm,
  Drawer,
  Space,
  Avatar,
  Dropdown,
} from "antd";
import {
  LikeOutlined,
  LikeFilled,
  MessageOutlined,
  DeleteOutlined,
  UserOutlined,
} from "@ant-design/icons";
import service from "@/http/request";
import dayjs from "dayjs";
import PostFooter from "@/components/PostFooter";

const { Title, Paragraph, Text } = Typography;
const { TextArea } = Input;

const PostDetail = () => {
  const [open, setOpen] = useState(false);

  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };

  const { id } = useParams(); // 获取 postId
  const [post, setPost] = useState(null);
  const [loading, setLoading] = useState(true);
  const [liked, setLiked] = useState(false);
  const [likeCount, setLikeCount] = useState(0);
  const [commentList, setCommentList] = useState([]);
  const [commentText, setCommentText] = useState("");
  const [pageNum, setPageNum] = useState(1);
  const pageSize = 10;
  const userName = useSelector((state) => state.user.userName);
  const Role = useSelector((state) => state.user.role);

  useEffect(() => {
    fetchPostDetail();
    fetchComments(1); // 默认第一页
  }, [id]);

  const fetchPostDetail = async () => {
    try {
      const res = await service.get(`/forum2/posts/${id}`);
      if (res) {
        setPost(res);
        setLiked(res.isLiked || false);
        setLikeCount(res.likeCount || 0);
      } else {
        message.error("获取帖子详情失败");
      }
    } catch (error) {
      console.error("获取帖子失败", error);
      message.error("获取帖子详情出错");
    } finally {
      setLoading(false);
    }
  };

  const fetchComments = async (page) => {
    try {
      const res = await service.get(`/forum2/posts/${id}/comments`, {
        params: { pageNum: page, pageSize },
      });
      console.log(res);
      setCommentList(res?.records || []);
      setPageNum(page);
    } catch (error) {
      console.error("获取评论失败", error);
      message.error("获取评论失败");
    }
  };

  const handleLike = async () => {
    if (liked) {
      message.info("你已经点过赞了！");
      return;
    }
    try {
      await service.post(`/forum2/posts/${id}/like`);
      setLiked(true);
      setLikeCount((prev) => prev + 1);
    } catch {
      message.error("点赞失败");
    }
  };

  const handleComment = async () => {
    if (!commentText.trim()) {
      message.warning("评论内容不能为空");
      return;
    }
    try {
      await service.post(`/forum2/posts/${id}/comments`, {
        content: commentText,
      });
      setCommentText("");
      fetchComments(1); // 重新拉取第一页
      message.success("评论成功");
    } catch {
      message.error("评论失败");
    }
  };

  const handleDeleteComment = async (item) => {
    try {
      console.log(item);
      const res = await service.delete(`/forum2/comments/${item.commentId}`);
      console.log(res);
      message.success("删除成功");
      fetchComments(pageNum);
    } catch {
      message.error("删除失败");
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: "center", marginTop: 100 }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!post) {
    return (
      <div style={{ textAlign: "center", marginTop: 100 }}>未找到帖子</div>
    );
  }

  const getAvatarItems = (userId) => [
    {
      key: "speak",
      label: <a href={`/messagelist/${userId}`}>私信</a>,
    },
  ];
  return (
    <div style={{ maxWidth: 900, margin: "40px auto", padding: "20px 10px" }}>
      <Title level={2} style={{ textAlign: "center" }}>
        {post.title}
      </Title>

      <div style={{ marginBottom: 20, textAlign: "center" }}>
        <Text type="secondary">作者：{post.username}</Text>
        <br />
        <Text type="secondary">
          发布时间：{new Date(post.createdAt).toLocaleString()}
        </Text>
        <br />
        <Text type="secondary">
          浏览：{post.viewCount}　点赞：{likeCount}
        </Text>
      </div>

      <MDEditor.Markdown
        source={post.content}
        style={{ fontSize: 16, background: "#fff", padding: 10 }}
      />

      <div
        style={{
          padding: "12px 16px",
          borderTop: "1px solid #f0f0f0",
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        {/* 用户信息区域 */}
        <Space align="center">
          <Avatar size="small" src="/avatar.jpg" icon={<UserOutlined />} />
          <Text strong>{userName}</Text>
          <Button size="small" type="default" ghost>
            已关注
          </Button>
        </Space>

        {/* 点赞和评论按钮 */}
        <Space size="middle">
          <Space>
            <span
              onClick={handleLike}
              style={{
                cursor: "pointer",
                fontSize: 20,
                transition: "transform 0.2s",
                color: liked ? "#eb2f96" : "#555",
              }}
            >
              {liked ? <LikeFilled /> : <LikeOutlined />} {likeCount}
            </span>
          </Space>
          <Space
            onClick={showDrawer}
            style={{
              cursor: "pointer",
            }}
          >
            <MessageOutlined />
            <span>评论</span>
          </Space>
        </Space>
      </div>

      <Drawer
        title="评论"
        closable={{ "aria-label": "Close Button" }}
        onClose={onClose}
        open={open}
        width={500}
      >
        {/* 评论输入 */}
        <div style={{ marginBottom: 30 }}>
          <TextArea
            rows={3}
            placeholder="写下你的评论..."
            value={commentText}
            onChange={(e) => setCommentText(e.target.value)}
          />
          <Button
            type="primary"
            style={{ marginTop: 10 }}
            onClick={handleComment}
          >
            发布评论
          </Button>
        </div>

        {/* 评论列表 */}
        <List
          dataSource={commentList}
          header={`${commentList.length} 条评论`}
          itemLayout="horizontal"
          renderItem={(item) => (
            <List.Item
              style={{ alignItems: "flex-start" }}
              actions={[
                Role === "ADMIN" || item.username === userName ? (
                  <Popconfirm
                    title="确定删除这条评论？"
                    onConfirm={() => handleDeleteComment(item)}
                    okText="是"
                    cancelText="否"
                  >
                    <DeleteOutlined style={{ color: "red" }} />
                  </Popconfirm>
                ) : (
                  <DeleteOutlined disabled />
                ),
              ]}
            >
              <List.Item.Meta
                title={
                  item.username === userName ? (
                    <div>
                      <Avatar
                        size="small"
                        src="/avatar.jpg"
                        icon={<UserOutlined />}
                      />{" "}
                      你{" "}
                    </div>
                  ) : (
                    <div
                      style={{
                        cursor: "pointer",
                      }}
                    >
                      <Dropdown menu={{ items: getAvatarItems(item.userId) }} placement="right">

                        <div>
                          <Avatar
                            size="small"
                            src="/avatar.jpg"
                            icon={<UserOutlined />}
                          />{" "}
                          {item.username || "匿名用户"}
                        </div>
                      </Dropdown>
                    </div>
                  )
                }
                description={item.content}
              />
              <div style={{ color: "#999", fontSize: 12, textAlign: "right" }}>
                {dayjs(item.createdAt).format("YYYY-MM-DD HH:mm:ss")}
              </div>
            </List.Item>
          )}
        />
      </Drawer>
    </div>
  );
};

export default PostDetail;
